import React, { useState, useEffect, Suspense, useMemo, useCallback } from 'react'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import 'antd/dist/reset.css'
import { useSelector, useDispatch } from 'react-redux'

import { accessAdded } from '@/store/features/access/accessSlicer'
import { RootState } from '@/store'
import { getEvaluatedRoutes } from '@/router'
import '@/assets/style/app.scss'
import { getAccess } from '@/service/user'

function App(): JSX.Element {
  const [routes, setRoutes] = useState(getEvaluatedRoutes())
  const access = useSelector((state: RootState) => state.access)
  const dispatch = useDispatch()
  const actionRoutes = useCallback(() => {
    if (access.length) {
      setRoutes(getEvaluatedRoutes(access))
    } else {
      getAccess().then((res) => {
        dispatch(accessAdded(res))
      })
    }
  }, [access])

  useEffect(() => {
    actionRoutes()
  }, [actionRoutes])

  const router = useMemo(() => createBrowserRouter(routes), [routes])

  return (
    <Suspense>
      <RouterProvider router={router} />
    </Suspense>
  )
}

export default App
